<?php

namespace iBrand\Component\Goods\Models;

use iBrand\Component\Discount\Contracts\DiscountItemContract;
use Illuminate\Database\Eloquent\Model;

class GoodsProduct extends Model implements DiscountItemContract
{
    protected $guarded = ['id'];

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $prefix = config('ibrand.app.database.prefix', 'ibrand_');

        $this->setTable($prefix . 'base_goods_product');
    }

    public function goods()
    {
        return $this->belongsTo(Goods::class, 'goods_id');
    }

    public function setSpecIDAttribute($value)
    {
        $this->attributes['specID'] = json_encode(explode('-', $value));
    }

    public function getSpecIDAttribute($value)
    {
        return json_decode($value);
    }

    public function scopeJudge($query, $sku, $id = 0)
    {
        return $query->where('sku', $sku)->where('id', '<>', $id)->get();
    }

    public function getFactoryPriceAttribute()
    {
        return $this->goods->factory_price;
    }

    public function getCategories()
    {
        return $this->goods->getCategories();
    }

    public function getKeyCode($type = 'sku')
    {
        if ($type == 'spu') {
            return $this->goods_id;
        }

        return $this->sku;
    }

    public function getItemType()
    {
        return 'product';
    }

    public function getChildKeyCodes()
    {
        return [];
    }

    public function getSeasonId()
    {
        return $this->goods->season_id;
    }
}